package com.primb.bench.project.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.flyco.dialog.widget.NormalDialog;
import com.primb.baselibs.util.FormatUtils;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.baselibs.view.loading.SpotsDialog;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.dialog.ListDialog;
import com.primb.bench.common.dialog.SelectListDialog;
import com.primb.bench.common.utils.RoleLevelConvert;
import com.primb.bench.common.viewmodel.ViewIconKVEntity;
import com.primb.bench.project.home.contract.LoanCalculateContract;
import com.primb.bench.project.home.entity.ApplyNextUserEntity;
import com.primb.bench.project.home.entity.ClientInfoEntity;
import com.primb.bench.project.home.entity.EnsureInfoEntity;
import com.primb.bench.project.home.entity.HttpResultEntity;
import com.primb.bench.project.home.entity.KeyEntity;
import com.primb.bench.project.home.entity.LoanCalculateInfoEntity;
import com.primb.bench.project.home.entity.LoanInfoEntity;
import com.primb.bench.project.home.entity.LogoInfoEntity;
import com.primb.bench.project.home.entity.PromiseApplyEntity;
import com.primb.bench.project.home.entity.TaxInfoEntity;
import com.primb.bench.project.home.presenter.LoanCalculatePresenterImpl;
import com.primb.netlibs.converter.RxSchedulerUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

/**
 * Created by Chen on 2017/5/5.
 * 功能描述：
 */

public class LoanCalculateActivity extends SwipeBaseActivity implements LoanCalculateContract.View {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.tv_logo_serial_number)
    TextView tvLogoSerialNumber;
    @BindView(R.id.iv_logo_edit)
    ImageView ivLogoEdit;
    @BindView(R.id.tv_calculate_logo_protocol_number)
    TextView tvCalculateLogoProtocolNumber;
    @BindView(R.id.tv_calculate_logo_manager_name)
    TextView tvCalculateLogoManagerName;
    @BindView(R.id.tv_calculate_logo_manager_number)
    TextView tvCalculateLogoManagerNumber;
    @BindView(R.id.tv_calculate_logo_part)
    TextView tvCalculateLogoPart;
    @BindView(R.id.tv_calculate_logo_date)
    TextView tvCalculateLogoDate;
    @BindView(R.id.tv_add_customer)
    TextView tvAddCustomer;
    @BindView(R.id.tv_calculate_customer_name)
    TextView tvCalculateCustomerName;
    @BindView(R.id.tv_calculate_customer_number)
    TextView tvCalculateCustomerNumber;
    @BindView(R.id.tv_calculate_customer_type)
    TextView tvCalculateCustomerType;
    @BindView(R.id.tv_calculate_credit)
    TextView tvCalculateCredit;
    @BindView(R.id.tv_calculate_size)
    TextView tvCalculateSize;
    @BindView(R.id.tv_calculate_all_contribution)
    TextView tvCalculateAllContribution;
    @BindView(R.id.tv_calculate_used_contribution)
    TextView tvCalculateUsedContribution;
    @BindView(R.id.tv_calculate_contribution_number)
    TextView tvCalculateContributionNumber;
    @BindView(R.id.tv_calculate_is_contribution)
    TextView tvCalculateIsContribution;
    @BindView(R.id.tv_calculate_all_profit)
    TextView tvCalculateAllProfit;
    @BindView(R.id.tv_calculate_rate_adjust)
    TextView tvCalculateRateAdjust;
    @BindView(R.id.layout_customer_content)
    LinearLayout layoutCustomerContent;
    @BindView(R.id.layout_calculate_customer)
    CardView layoutCalculateCustomer;
    @BindView(R.id.tv_add_loan)
    TextView tvAddLoan;
    @BindView(R.id.tv_calculate_loan_money)
    TextView tvCalculateLoanMoney;
    @BindView(R.id.tv_calculate_loan_date)
    TextView tvCalculateLoanDate;
    @BindView(R.id.tv_calculate_loan_type)
    TextView tvCalculateLoanType;
    @BindView(R.id.tv_calculate_loan_business_type)
    TextView tvCalculateLoanBusinessType;
    @BindView(R.id.tv_calculate_loan_industry)
    TextView tvCalculateLoanIndustry;
    @BindView(R.id.tv_calculate_loan_rate_type)
    TextView tvCalculateLoanRateType;
    @BindView(R.id.layout_loan_content)
    LinearLayout layoutLoanContent;
    @BindView(R.id.layout_calculate_loan)
    CardView layoutCalculateLoan;
    @BindView(R.id.tv_add_ensure)
    TextView tvAddEnsure;
    @BindView(R.id.tv_calculate_ensure_main_type)
    TextView tvCalculateEnsureMainType;
    @BindView(R.id.tv_calculate_ensure_concreteness_type)
    TextView tvCalculateEnsureConcretenessType;
    @BindView(R.id.layout_ensure_money)
    LinearLayout layoutCalculateEnsureMoney;
    @BindView(R.id.layout_ensure_content)
    LinearLayout layoutEnsureContent;
    @BindView(R.id.layout_calculate_ensure)
    CardView layoutCalculateEnsure;
    @BindView(R.id.et_calculate_tax_vat)
    EditText etCalculateTaxVat;
    @BindView(R.id.tv_calculate_tax_income)
    TextView tvCalculateTaxIncome;
    @BindView(R.id.layout_tax_content)
    LinearLayout layoutTaxContent;
    @BindView(R.id.layout_calculate_tax)
    CardView layoutCalculateTax;
    @BindView(R.id.btn_calculate_measure)
    Button btnCalculateMeasure;
    @BindView(R.id.tv_calculate_result_all_cost_rate)
    TextView tvCalculateResultAllCostRate;
    @BindView(R.id.tv_calculate_result_change_cost_rate)
    TextView tvCalculateResultChangeCostRate;
    @BindView(R.id.tv_calculate_result_target_rate)
    TextView tvCalculateResultTargetRate;
    @BindView(R.id.tv_calculate_result_direct_rate)
    TextView tvCalculateResultDirectRate;
    @BindView(R.id.tv_calculate_result_reference_rate)
    TextView tvCalculateResultReferenceRate;
    @BindView(R.id.btn_calculate_promise)
    Button btnCalculatePromise;
    @BindView(R.id.btn_calculate_save)
    Button btnCalculateSave;
    @BindView(R.id.et_calculate_apply_rate)
    EditText etCalculateApplyRate;
    @BindView(R.id.et_calculate_apply_reason)
    EditText etCalculateApplyReason;
    @BindView(R.id.btn_calculate_apply)
    Button btnCalculateApply;
    @BindView(R.id.layout_result_content)
    CardView layoutResultContent;
    @BindView(R.id.scroll_calculate)
    ScrollView scrollCalculate;
    @BindView(R.id.tv_calculate_promise_list)
    TextView tvCalculatePromiseList;
    @BindView(R.id.et_calculate_promise_cash)
    EditText etCalculatePromiseCash;
    @BindView(R.id.tv_calculate_promise_rate)
    TextView tvCalculatePromiseRate;
    @BindView(R.id.layout_calculate_promise)
    CardView layoutCalculatePromise;
    @BindView(R.id.layout_calculate_apply)
    CardView layoutCalculateApply;
    @BindView(R.id.layout_calculate_promise_detail)
    LinearLayout layoutCalculatePromiseDetail;
    @BindView(R.id.tv_calculate_promise_start_date)
    TextView tvCalculatePromiseStartDate;
    @BindView(R.id.tv_calculate_promise_end_date)
    TextView tvCalculatePromiseEndDate;
    @BindView(R.id.tv_calculate_promise_deposit_day_now)
    TextView tvCalculatePromiseDepositDayNow;
    @BindView(R.id.tv_calculate_promise_deposit_day)
    TextView tvCalculatePromiseDepositDay;
    @BindView(R.id.tv_calculate_promise_deposit_sum_now)
    TextView tvCalculatePromiseDepositSumNow;
    @BindView(R.id.tv_calculate_promise_deposit_sum)
    TextView tvCalculatePromiseDepositSum;
    @BindView(R.id.tv_calculate_promise_basic_account)
    TextView tvCalculatePromiseBasicAccount;
    @BindView(R.id.tv_calculate_promise_settle_account)
    TextView tvCalculatePromiseSettleAccount;
    @BindView(R.id.tv_calculate_promise_salary_account)
    TextView tvCalculatePromiseSalaryAccount;
    @BindView(R.id.tv_calculate_promise_other_scene)
    TextView tvCalculatePromiseOtherScene;
    @BindView(R.id.tv_calculate_promise_other_scene_detail)
    TextView tvCalculatePromiseOtherSceneDetail;
    @BindView(R.id.tv_calculate_promise_remark)
    TextView tvCalculatePromiseRemark;
    @BindView(R.id.tv_calculate_promise_favorable_rate)
    TextView tvCalculatePromiseFavorableRate;
    @BindView(R.id.tv_calculate_promise_point)
    TextView tvCalculatePromisePoint;
    @BindView(R.id.iv_calculate_customer_icon)
    ImageView ivCalculateCustomerIcon;
    @BindView(R.id.tv_calculate_parent_contribution)
    ImageView tvCalculateParentContribution;
    @BindView(R.id.layout_parent_contribution)
    RelativeLayout layoutParentContribution;
    @BindView(R.id.layout_logo_number)
    LinearLayout layoutLogoNumber;
    @BindView(R.id.tv_calculate_is_contribution_parent)
    TextView tvCalculateIsContributionParent;
    @BindView(R.id.tv_calculate_all_profit_parent)
    TextView tvCalculateAllProfitParent;
    @BindView(R.id.tv_calculate_all_contribution_parent)
    TextView tvCalculateAllContributionParent;
    @BindView(R.id.tv_calculate_used_contribution_parent)
    TextView tvCalculateUsedContributionParent;
    @BindView(R.id.tv_calculate_contribution_number_parent)
    TextView tvCalculateContributionNumberParent;
    @BindView(R.id.tv_calculate_debt_parent)
    TextView tvCalculateDebtParent;
    @BindView(R.id.layout_calculate_customer_parent)
    LinearLayout layoutCalculateCustomerParent;
    @BindView(R.id.iv_calculate_loan_icon)
    ImageView ivCalculateLoanIcon;
    @BindView(R.id.tv_calculate_loan_repayment)
    TextView tvCalculateLoanRepayment;
    @BindView(R.id.layout_result_change_cost_rate)
    RelativeLayout layoutResultChangeCostRate;
    @BindView(R.id.line_result_change_cost_rate)
    View lineResultChangeCostRate;
    @BindView(R.id.layout_result_all_cost_rate)
    RelativeLayout layoutResultAllCostRate;
    @BindView(R.id.line_result_all_cost_rate)
    View lineResultAllCostRate;
    @BindView(R.id.layout_result_target_rate)
    RelativeLayout layoutResultTargetRate;
    @BindView(R.id.line_result_target_rate)
    View lineResultTargetRate;
    private SpotsDialog spotsDialog;
    private LoanCalculatePresenterImpl mPresenter;
    private Handler mHandler = new Handler();
    private boolean isStock = false;
    private boolean isShowResult = false;
    private int type;
    public static final String KEY_SCENE_NEW = "L05001";
    public static final String KEY_SCENE_STOCK = "L05002";
    public static final String KEY_PRICE_CALCULATE = "01";
    public static final String KEY_PRICE_MEASURE = "02";
    private ListDialog listDialog;
    ViewIconKVEntity editKVEntity;
    boolean isImageView = true;

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_loan_calculate;
    }

    @Override
    protected void onBaseBindView() {
        toolBar.setNavigationOnClickListener(v -> LoanCalculateActivity.this.finish());
        titleBar.setText("新增贷款试算");
        ivTop.setImageResource(R.mipmap.reset_icon);
        etCalculatePromiseCash.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (!s.toString().isEmpty() && !s.equals("0")) {
                        Double valueOf = Double.valueOf(s.toString());
                        if (valueOf > 10) {
                            showError("请输入不大于10的调节值");
                            etCalculatePromiseCash.setText("");
                            return;
                        }
                        Double targetRate = Double.valueOf(mPresenter.infoEntity.getResultInfoEntity().getLnpTargetRate()) * 100;
                        tvCalculatePromiseRate.setText(FormatUtils.format(valueOf + targetRate));
                        mPresenter.infoEntity.getPromiseApplyEntity().setPromiseAdjustDirectRate((valueOf + targetRate) / 100 + "");
                        mPresenter.infoEntity.getPromiseApplyEntity().setPromiseAdjustRate(valueOf / 100 + "");
                    } else {
                        Double targetRate = Double.valueOf(mPresenter.infoEntity.getResultInfoEntity().getLnpTargetRate()) * 100;
                        tvCalculatePromiseRate.setText(FormatUtils.format(targetRate));
                        mPresenter.infoEntity.getPromiseApplyEntity().setPromiseAdjustRate("0");
                    }
                } catch (Exception e) {
                    showError("请输入正确格式的调节值");
                }
            }
        });
        layoutCalculateCustomer.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!isStock && mPresenter.infoEntity.getClientInfoEntity() != null) {
                    Intent intent = new Intent();
                    intent.setClass(LoanCalculateActivity.this, LoanClientActivity.class);
                    intent.putExtra("info", mPresenter.infoEntity.getClientInfoEntity());
                    startActivityForResult(intent, AppConstant.LOAN_CUSTOMER_REQUEST);
                }
                return false;
            }
        });

        tvCalculateTaxIncome.setOnClickListener(v -> {
            SelectListDialog selectListDialog = showPickerDialog();
            Observable.timer(100, TimeUnit.MILLISECONDS)
                    .compose(RxSchedulerUtils.normalSchedulersTransformer())
                    .subscribe(aLong -> {
                        ArrayList<KeyEntity> list = new ArrayList<>();
                        list.add(new KeyEntity("0", "0"));
                        list.add(new KeyEntity("25", "25"));
                        selectListDialog.setDateList(list);
                    });
        });

        btnCalculatePromise.setTag(false);
    }

    public SelectListDialog showPickerDialog() {
        SelectListDialog selectListDialog = new SelectListDialog();
        selectListDialog.setListener((adapter, v, position) -> {
            List<KeyEntity> dataList = selectListDialog.getDataList();
            mPresenter.infoEntity.getTaxInfoEntity().setTaxIncome(dataList.get(position).getKey());
            tvCalculateTaxIncome.setText(FormatUtils.format(dataList.get(position).getKey()));
            selectListDialog.dismiss();
        });
        selectListDialog.show(getSupportFragmentManager());
        return selectListDialog;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.handleResultInfo(requestCode, resultCode, data);
    }

    @Override
    protected void onLoadData() {
        mPresenter = new LoanCalculatePresenterImpl(this, this);
        Intent intent = getIntent();
        type = intent.getIntExtra("type", AppConstant.LOAN_CALCULATE);
        LoanCalculateInfoEntity infoStock = intent.getParcelableExtra("info");
        ivLogoEdit.setVisibility(View.GONE);
        mPresenter.setLogoType(KEY_SCENE_NEW, KEY_PRICE_CALCULATE);
        switch (type) {
            case AppConstant.LOAN_CALCULATE:
                titleBar.setText("新增贷款试算");
                if (infoStock != null) {
                    showCalculateInfo(infoStock);
                    mPresenter.infoEntity = infoStock;
                    isStock = true;
                    titleBar.setText("贷款续作试算");
                    mPresenter.setLogoType(KEY_SCENE_STOCK, KEY_PRICE_CALCULATE);
                }
                break;
            case AppConstant.LOAN_PRICE:
                titleBar.setText("新增贷款定价");
                mPresenter.setLogoType(KEY_SCENE_NEW, KEY_PRICE_MEASURE);
                if (infoStock != null) {
                    showCalculateInfo(infoStock);
                    mPresenter.infoEntity = infoStock;
                    isStock = true;
                    titleBar.setText("贷款续作定价");
                    mPresenter.setLogoType(KEY_SCENE_STOCK, KEY_PRICE_MEASURE);
//                    ivLogoEdit.setVisibility(View.VISIBLE);
                }
                break;
        }
        if (!isStock) {
            mPresenter.start();
        }
    }

    @OnClick({R.id.iv_top, R.id.iv_logo_edit, R.id.btn_calculate_measure, R.id.layout_calculate_customer, R.id.layout_calculate_loan,
            R.id.layout_calculate_ensure, R.id.btn_calculate_save, R.id.tv_calculate_result_parameter,
            R.id.tv_calculate_promise_list, R.id.btn_calculate_promise, R.id.btn_calculate_apply, R.id.tv_calculate_promise_delete})
    public void onViewClicked(View view) {
        mPresenter.onViewClick(view.getId(), isShowResult);
    }

    @Override
    public void showResultView(HttpResultEntity.DataBean bean) {
        try {
            if (AppConstant.ROLE_LEVEL_ENUM == RoleLevelConvert.RoleLevel.MANAGER) {
                layoutResultAllCostRate.setVisibility(View.GONE);
                layoutResultChangeCostRate.setVisibility(View.GONE);
                layoutResultTargetRate.setVisibility(View.GONE);

                lineResultAllCostRate.setVisibility(View.GONE);
                lineResultChangeCostRate.setVisibility(View.GONE);
                lineResultTargetRate.setVisibility(View.GONE);
            } else if (AppConstant.ROLE_LEVEL_ENUM == RoleLevelConvert.RoleLevel.DEPARTMENT) {
                layoutResultAllCostRate.setVisibility(View.VISIBLE);
                layoutResultChangeCostRate.setVisibility(View.GONE);
                layoutResultTargetRate.setVisibility(View.VISIBLE);

                lineResultAllCostRate.setVisibility(View.VISIBLE);
                lineResultChangeCostRate.setVisibility(View.GONE);
                lineResultTargetRate.setVisibility(View.VISIBLE);
            } else {
                layoutResultAllCostRate.setVisibility(View.VISIBLE);
                layoutResultChangeCostRate.setVisibility(View.VISIBLE);
                layoutResultTargetRate.setVisibility(View.VISIBLE);

                lineResultAllCostRate.setVisibility(View.VISIBLE);
                lineResultChangeCostRate.setVisibility(View.VISIBLE);
                lineResultTargetRate.setVisibility(View.VISIBLE);
            }
            tvCalculateResultAllCostRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpCostRate()) * 100));
            tvCalculateResultChangeCostRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpCostBdRate()) * 100));
            tvCalculateResultDirectRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpCustRate()) * 100));
            tvCalculateResultTargetRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpTargetRate()) * 100));
            tvCalculateResultReferenceRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpMarketIr()) * 100));
            tvCalculatePromiseRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpTargetRate()) * 100));
        } catch (NumberFormatException e) {
            showAlterDialogOne("提示", "测算结果数据格式异常，请联系管理员解决");
            return;
        }
        ivTop.setVisibility(View.VISIBLE);
        layoutResultContent.setVisibility(View.VISIBLE);
        btnCalculateMeasure.setVisibility(View.GONE);
        mHandler.postDelayed(() -> {
            int top = layoutResultContent.getTop();
            scrollCalculate.smoothScrollTo(0, top);
        },100);
        layoutCalculatePromise.setVisibility(View.VISIBLE);
        isShowResult = true;
        if (type == AppConstant.LOAN_CALCULATE) {
            btnCalculateSave.setVisibility(View.VISIBLE);
        } else {
            btnCalculateSave.setVisibility(View.GONE);
        }

        ivCalculateCustomerIcon.setVisibility(View.GONE);
        ivCalculateLoanIcon.setVisibility(View.GONE);
        if (!isImageView) {
            editKVEntity.getImageEdit().setVisibility(View.GONE);
        } else {
            layoutCalculateEnsureMoney.setVisibility(View.GONE);
        }

        etCalculateTaxVat.setEnabled(false);
//        tvCalculateResultAllCostRate.setText(bean.getLnpCostRate());
//        tvCalculateResultChangeCostRate.setText(bean.getLnpCostBdRate());
//        tvCalculateResultDirectRate.setText(bean.getLnpCustRate());
//        tvCalculateResultTargetRate.setText(bean.getLnpTargetRate());
//        tvCalculateResultReferenceRate.setText(bean.getLnpMarketIr());
//        tvCalculatePromiseRate.setText(bean.getLnpTargetRate());
    }

    @Override
    public void hideResultView() {
        layoutResultContent.setVisibility(View.GONE);
        btnCalculateMeasure.setVisibility(View.VISIBLE);
        mHandler.postDelayed(() -> {
            int top = btnCalculateMeasure.getTop();
            scrollCalculate.smoothScrollTo(0, top);
        },100);
        layoutCalculatePromise.setVisibility(View.GONE);
        layoutCalculateApply.setVisibility(View.GONE);
        isShowResult = false;

        ivCalculateCustomerIcon.setVisibility(View.VISIBLE);
        ivCalculateLoanIcon.setVisibility(View.VISIBLE);

        if (!isImageView) {
            editKVEntity.getImageEdit().setVisibility(View.VISIBLE);
        } else {
            layoutCalculateEnsureMoney.setVisibility(View.VISIBLE);
        }

        etCalculateTaxVat.setEnabled(true);
    }

    @Override
    public void intentToAddInfo(int requestCode) {
        Intent intent = new Intent();
        if (requestCode == AppConstant.LOAN_CUSTOMER_REQUEST && !isStock) {
            if (mPresenter.infoEntity.getClientInfoEntity() != null) {
                intent.setClass(LoanCalculateActivity.this, AddInfoActivity.class);
                intent.putExtra("info", mPresenter.infoEntity.getClientInfoEntity());
            } else {
                intent.setClass(LoanCalculateActivity.this, LoanClientActivity.class);
            }
        } else {
            intent.setClass(LoanCalculateActivity.this, AddInfoActivity.class);
        }
        intent.putExtra("code", requestCode);
        switch (requestCode) {
            case AppConstant.LOAN_CUSTOMER_REQUEST:
                if (mPresenter.infoEntity.getClientInfoEntity() != null && isStock) {
                    intent.putExtra("info", mPresenter.infoEntity.getClientInfoEntity());
                }
                break;
            case AppConstant.LOAN_LOAN_REQUEST:
                if (mPresenter.infoEntity.getLoanInfoEntity() != null) {
                    intent.putExtra("info", mPresenter.infoEntity.getLoanInfoEntity());
                }
                intent.putExtra("clientType", mPresenter.infoEntity.getClientInfoEntity().getCustomerTypeId());
                break;
            case AppConstant.LOAN_ENSURE_REQUEST:
                if (mPresenter.infoEntity.getEnsureInfoEntity() != null) {
                    intent.putExtra("info", mPresenter.infoEntity.getEnsureInfoEntity());
                }
                intent.putExtra("priceId", mPresenter.infoEntity.getLogoInfoEntity().getLogoNumber());
                break;
            case AppConstant.LOAN_TAX_REQUEST:
                if (mPresenter.infoEntity.getEnsureInfoEntity() != null) {
                    intent.putExtra("info", mPresenter.infoEntity.getTaxInfoEntity());
                }
                break;
            default:
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void intentToMain() {
        if (listDialog != null) {
            listDialog.dismiss();
        }
        this.finish();
    }

    @Override
    public void intentToPromise(int requestCode) {
        Intent intent = new Intent(this, PromiseApplyActivity.class);
        intent.putExtra("info", mPresenter.infoEntity);
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void intentToParameter(HttpResultEntity.DataBean bean) {
        Intent intent = new Intent(this, LoanParameterActivity.class);
        intent.putExtra("info", bean);
        startActivity(intent);
    }

    @Override
    public void intentToPromiseList() {
        Intent intent = new Intent(this, LoanPromiseActivity.class);
        intent.putExtra("info", mPresenter.infoEntity.getClientInfoEntity().getCustomerNum());
        startActivity(intent);
    }

    @Override
    public void showCustomerAddInfo() {
        layoutCalculateCustomer.setVisibility(View.VISIBLE);
        tvAddCustomer.setVisibility(View.VISIBLE);
    }

    @Override
    public void showCustomerInfo() {
        if (!isStock && mPresenter.infoEntity.getLoanInfoEntity() == null) {
            layoutResultContent.setVisibility(View.GONE);
            layoutCalculatePromise.setVisibility(View.GONE);
            layoutCalculateApply.setVisibility(View.GONE);
            btnCalculateMeasure.setVisibility(View.GONE);
            layoutCalculateLoan.setVisibility(View.VISIBLE);
            tvAddLoan.setVisibility(View.VISIBLE);
            layoutLoanContent.setVisibility(View.GONE);
            mHandler.postDelayed(() -> {
                int top = layoutCalculateLoan.getTop();
                scrollCalculate.smoothScrollTo(0, top);
            },100);
            layoutCustomerContent.setVisibility(View.VISIBLE);
            tvAddCustomer.setVisibility(View.GONE);
        }
    }

    @Override
    public void changeCustomerInfo() {
        if (!isStock) {
            layoutResultContent.setVisibility(View.GONE);
            layoutCalculatePromise.setVisibility(View.GONE);
            layoutCalculateApply.setVisibility(View.GONE);
            btnCalculateMeasure.setVisibility(View.GONE);
            layoutCalculateEnsureMoney.setVisibility(View.GONE);
            layoutCalculateEnsure.setVisibility(View.GONE);
            layoutCalculateTax.setVisibility(View.GONE);
            layoutCalculateLoan.setVisibility(View.VISIBLE);
            tvAddLoan.setVisibility(View.VISIBLE);
            layoutLoanContent.setVisibility(View.GONE);
            mHandler.postDelayed(() -> {
                int top = layoutCalculateLoan.getTop();
                scrollCalculate.smoothScrollTo(0, top);
            },100);
            layoutCustomerContent.setVisibility(View.VISIBLE);
            tvAddCustomer.setVisibility(View.GONE);
        }
    }

    @Override
    public void showLoanInfo() {
        if (!isStock && mPresenter.infoEntity.getLoanInfoEntity() == null) {
            layoutResultContent.setVisibility(View.GONE);
            layoutCalculatePromise.setVisibility(View.GONE);
            layoutCalculateApply.setVisibility(View.GONE);
            btnCalculateMeasure.setVisibility(View.GONE);
            layoutCalculateEnsure.setVisibility(View.VISIBLE);
            tvAddEnsure.setVisibility(View.VISIBLE);
            layoutEnsureContent.setVisibility(View.GONE);
            layoutLoanContent.setVisibility(View.VISIBLE);
            tvAddLoan.setVisibility(View.GONE);
            mHandler.postDelayed(() -> {
                int top = layoutCalculateEnsure.getTop();
                scrollCalculate.smoothScrollTo(0, top);
            },100);
        }
    }

    @Override
    public void showEnsureInfo() {
        if (!isStock) {
            layoutResultContent.setVisibility(View.GONE);
            layoutCalculatePromise.setVisibility(View.GONE);
            layoutCalculateApply.setVisibility(View.GONE);
            layoutCalculateEnsure.setVisibility(View.VISIBLE);
            layoutCalculateTax.setVisibility(View.VISIBLE);
            layoutEnsureContent.setVisibility(View.VISIBLE);
            tvAddEnsure.setVisibility(View.GONE);
//            mHandler.post(() -> {
//                int top = btnCalculateMeasure.getTop();
////                scrollCalculate.smoothScrollTo(0, top);
//                scrollCalculate.fullScroll(ScrollView.FOCUS_DOWN);
//            });
        }
    }

    @Override
    public void showTaxInfo() {
        btnCalculateMeasure.setVisibility(View.VISIBLE);
        if (!isStock) {
            layoutResultContent.setVisibility(View.GONE);
            layoutCalculatePromise.setVisibility(View.GONE);
            layoutCalculateApply.setVisibility(View.GONE);
            layoutTaxContent.setVisibility(View.VISIBLE);
            mHandler.postDelayed(() -> {

                int top = layoutCalculateTax.getTop();
                int visibility = btnCalculateMeasure.getVisibility();
//                scrollCalculate.smoothScrollTo(0, top);
                scrollCalculate.fullScroll(ScrollView.FOCUS_DOWN);
            }, 100);
        }
    }

    @Override
    public void setInfoToLogo(LogoInfoEntity entity) {
        tvLogoSerialNumber.setText(entity.getLogoNumber());
        tvCalculateLogoDate.setText(entity.getLogoDate());
        tvCalculateLogoManagerName.setText(entity.getLogoManagerName());
        tvCalculateLogoManagerNumber.setText(entity.getLogoManagerNum());
        tvCalculateLogoPart.setText(entity.getLogoPart());
        if (entity.getLogoProtocolNum() != null && !entity.getLogoProtocolNum().equals("")) {
            tvCalculateLogoProtocolNumber.setText(entity.getLogoProtocolNum());
            layoutLogoNumber.setVisibility(View.VISIBLE);
        } else {
            layoutLogoNumber.setVisibility(View.GONE);
        }
    }

    @Override
    public void setInfoToCustomer(ClientInfoEntity entity) {
        tvAddCustomer.setVisibility(View.GONE);
        layoutCalculateCustomer.setVisibility(View.VISIBLE);
        tvCalculateCustomerName.setText(entity.getCustomerName());
        tvCalculateCustomerNumber.setText(entity.getCustomerNum());
        tvCalculateCustomerType.setText(entity.getCustomerType());
        tvCalculateCredit.setText(entity.getCustomerCredit());
        tvCalculateSize.setText(entity.getCustomerSize());
        tvCalculateContributionNumber.setText(entity.getCustomerContributionNum());
        tvCalculateAllContribution.setText(entity.getCustomerAllContribution());
        tvCalculateIsContribution.setText(entity.getCustomerIsContribution().equals("0") ? "否" : "是");
        tvCalculateUsedContribution.setText(entity.getCustomerUsedContribution());
        tvCalculateRateAdjust.setText(entity.getCustomerAdjustRate());
        tvCalculateAllProfit.setText(entity.getCustomerAllProfit());
        tvCalculateParentContribution.setBackgroundResource(entity.getCustomerIsContributionM().equals("0") ? R.mipmap.client_point_normal : R.mipmap.client_point_select);
        layoutParentContribution.setVisibility(entity.getCustomerIsContributionM().equals("0") ? View.GONE : View.VISIBLE);
    }

    @Override
    public void setInfoToLoan(LoanInfoEntity entity) {
        tvCalculateLoanMoney.setText(FormatUtils.format2Int(entity.getLoanMoney()));
        tvCalculateLoanDate.setText(entity.getLoanDate() + entity.getLoanDateUnit());
        tvCalculateLoanBusinessType.setText(entity.getLoanBusinessType());
        tvCalculateLoanType.setText(entity.getLoanType());
        tvCalculateLoanRepayment.setText(entity.getLoanRepayment());
        tvCalculateLoanIndustry.setText(entity.getLoanIndustry() == null || entity.getLoanIndustry().equals("") ? "-" : entity.getLoanIndustry());
        tvCalculateLoanRateType.setText(entity.getLoanRateType() == null || entity.getLoanRateType().equals("") ? "-" : entity.getLoanRateType());
    }

    @Override
    public void setInfoToEnsure(EnsureInfoEntity entity) {
        tvCalculateEnsureMainType.setText(entity.getEnsureMainType());
        if (entity.getEnsureConcretenessType() != null && !TextUtils.isEmpty(entity.getEnsureConcretenessType())) {
            {
                tvCalculateEnsureConcretenessType.setText(entity.getEnsureConcretenessType());
            }
        } else {
            tvCalculateEnsureConcretenessType.setText("-");
        }
        layoutCalculateEnsureMoney.removeAllViews();
        layoutCalculateEnsureMoney.setVisibility(View.VISIBLE);
        layoutCalculateEnsureMoney.setBackgroundColor(ContextCompat.getColor(this, R.color.calculate_bg));

        isImageView = true;
        if (!entity.getLnFinImpawnAmt().equals("0")) {
            ViewIconKVEntity finKVEntity = new ViewIconKVEntity("金融质押品金额", FormatUtils.format2Int(entity.getLnFinImpawnAmt()));
            finKVEntity.addView(this, layoutCalculateEnsureMoney, isImageView);
            editKVEntity = finKVEntity;
            isImageView = false;
        } else if (!entity.getLnAcctRecvAmt().equals("0")) {
            ViewIconKVEntity acctKVEntity = new ViewIconKVEntity("应收账款金额", FormatUtils.format2Int(entity.getLnAcctRecvAmt()));
            acctKVEntity.addView(this, layoutCalculateEnsureMoney, isImageView);
            if (isImageView) {
                editKVEntity = acctKVEntity;
            }
            isImageView = false;
        } else if (!entity.getLnPropertyAmt().equals("0")) {
            ViewIconKVEntity propKVEntity = new ViewIconKVEntity("商业或居住用房地金额", FormatUtils.format2Int(entity.getLnPropertyAmt()));
            propKVEntity.addView(this, layoutCalculateEnsureMoney, isImageView);
            if (isImageView) {
                editKVEntity = propKVEntity;
            }
            isImageView = false;
        } else if (!entity.getLnOthMortAmt().equals("0")) {
            ViewIconKVEntity otherKVEntity = new ViewIconKVEntity("其它抵质押品金额", FormatUtils.format2Int(entity.getLnOthMortAmt()));
            otherKVEntity.addView(this, layoutCalculateEnsureMoney, isImageView);
            if (isImageView) {
                editKVEntity = otherKVEntity;
            }
            isImageView = false;
        } else if (!entity.getHighGuarantee().equals("0")) {
            ViewIconKVEntity highKVEntity = new ViewIconKVEntity("优质保证金额", FormatUtils.format2Int(entity.getHighGuarantee()));
            highKVEntity.addView(this, layoutCalculateEnsureMoney, isImageView);
            if (isImageView) {
                editKVEntity = highKVEntity;
            }
            isImageView = false;
        } else if (!entity.getCommonGuarantee().equals("0")) {
            ViewIconKVEntity comKVEntity = new ViewIconKVEntity("一般保证金额", FormatUtils.format2Int(entity.getCommonGuarantee()));
            comKVEntity.addView(this, layoutCalculateEnsureMoney, isImageView);
            if (isImageView) {
                editKVEntity = comKVEntity;
            }
            isImageView = false;
        } else {
            layoutCalculateEnsureMoney.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
            ViewIconKVEntity iconKVEntity = new ViewIconKVEntity();
            iconKVEntity.addView(this, layoutCalculateEnsureMoney);
            if (isImageView) {
                editKVEntity = iconKVEntity;
            }
        }
    }

    @Override
    public void setInfoToTax(TaxInfoEntity entity) {
        etCalculateTaxVat.setText(FormatUtils.format(entity.getTaxVat()));
        tvCalculateTaxIncome.setText(FormatUtils.format(entity.getTaxIncome()));
    }

    @Override
    public void getInfoToTax(TaxInfoEntity entity) {
        entity.setTaxVat(etCalculateTaxVat.getText().toString());
        entity.setTaxIncome(tvCalculateTaxIncome.getText().toString());
    }

    @Override
    public void setInfoToPromise(PromiseApplyEntity entity) {
        layoutCalculatePromiseDetail.setVisibility(View.VISIBLE);
        btnCalculatePromise.setVisibility(View.GONE);
        tvCalculatePromiseDepositDay.setText(entity.getPromiseDepositDay());
        tvCalculatePromiseDepositDayNow.setText(entity.getPromiseDepositDayNow());
        tvCalculatePromiseDepositSum.setText(entity.getPromiseDepositSum());
        tvCalculatePromiseDepositSumNow.setText(entity.getPromiseDepositSumNow());
        tvCalculatePromiseEndDate.setText(entity.getPromiseEndDate());
        tvCalculatePromiseStartDate.setText(entity.getPromiseStartDate());
        tvCalculatePromiseFavorableRate.setText(FormatUtils.format(Double.valueOf(entity.getPromiseFavorableRate()) * 100));
        tvCalculatePromiseOtherScene.setText(entity.getPromiseOtherScene());
        tvCalculatePromiseOtherSceneDetail.setText(entity.getPromiseOtherSceneDetail());
        tvCalculatePromisePoint.setText(entity.getPromisePoint());
        tvCalculatePromiseRemark.setText(entity.getPromiseRemark());
        tvCalculatePromiseSalaryAccount.setText(entity.isPromiseSalaryAccount() ? "是" : "否");
        tvCalculatePromiseSettleAccount.setText(entity.isPromiseSettleAccount() ? "是" : "否");
        tvCalculatePromiseBasicAccount.setText(entity.isPromiseBasicAccount() ? "是" : "否");

        if (etCalculatePromiseCash.getText().toString().isEmpty()) {
            entity.setPromiseAdjustRate("0");
            etCalculatePromiseCash.setText("0");
        } else {
            entity.setPromiseAdjustRate(etCalculatePromiseCash.getText().toString());
        }

        entity.setPromiseAdjustDirectRate(Double.valueOf(tvCalculatePromiseRate.getText().toString()) / 100 + "");
    }

    @Override
    public void hidePromiseInfo(PromiseApplyEntity infoEntity) {
        layoutCalculatePromiseDetail.setVisibility(View.GONE);
        btnCalculatePromise.setVisibility(View.VISIBLE);
        etCalculatePromiseCash.setEnabled(true);
        infoEntity.setPromiseDetail(false);

    }

    @Override
    public void showCalculateInfo(LoanCalculateInfoEntity entity) {
        layoutCalculateCustomer.setVisibility(View.VISIBLE);
        layoutCalculateLoan.setVisibility(View.VISIBLE);
        layoutCalculateEnsure.setVisibility(View.VISIBLE);
        layoutCalculateTax.setVisibility(View.VISIBLE);
        layoutCustomerContent.setVisibility(View.VISIBLE);
        layoutLoanContent.setVisibility(View.VISIBLE);
        layoutEnsureContent.setVisibility(View.VISIBLE);
        layoutTaxContent.setVisibility(View.VISIBLE);
        tvAddCustomer.setVisibility(View.GONE);
        tvAddEnsure.setVisibility(View.GONE);
        tvAddLoan.setVisibility(View.GONE);
        layoutCalculatePromiseDetail.setVisibility(View.GONE);
        btnCalculateMeasure.setVisibility(View.VISIBLE);
        btnCalculatePromise.setVisibility(View.VISIBLE);
        etCalculatePromiseCash.setEnabled(true);

        setInfoToLogo(entity.getLogoInfoEntity());
        setInfoToCustomer(entity.getClientInfoEntity());
        setInfoToLoan(entity.getLoanInfoEntity());
        setInfoToEnsure(entity.getEnsureInfoEntity());
        setInfoToTax(entity.getTaxInfoEntity());

        closePromiseEdit();
        closeTaxEdit();
    }

    @Override
    public void closeTaxEdit() {
        etCalculatePromiseCash.setEnabled(true);
    }

    @Override
    public void closePromiseEdit() {
        etCalculatePromiseCash.setEnabled(false);
    }

    @Override
    public boolean getApplyInfo(PromiseApplyEntity entity) {
        String applyRate = etCalculateApplyRate.getText().toString();
        if (applyRate.isEmpty()) {
            showError("申请利率不能为空");
            return false;
        }
        Double rate;
        try {
            rate = Double.valueOf(applyRate);
        } catch (NumberFormatException e) {
            showError("申请利率输入格式有误");
            return false;
        }
        if (rate <= 0) {
            showError("申请利率不能低于0");
            return false;
        }
// else if (rate < Double.valueOf(mPresenter.infoEntity.getResultInfoEntity().getLnpCostRate()) * 100) {
//            showError("申请利率低于全成本利率");
//        } else if (rate < Double.valueOf(mPresenter.infoEntity.getResultInfoEntity().getLnpTargetRate()) * 100) {
//            showError("申请利率低于目标利率");
//        } else if (rate < Double.valueOf(mPresenter.infoEntity.getResultInfoEntity().getLnpCustRate()) * 100) {
//            showError("申请利率低于指导利率");
//        }
        entity.setApplyRate(rate / 100 + "");
        entity.setApplyDate(FormatUtils.formatDate(new Date(), ""));
        entity.setApplyReason(etCalculateApplyReason.getText().toString());
        return true;
    }

    @Override
    public void showPersonList(ApplyNextUserEntity entity) {
        listDialog = new ListDialog(this, entity.getData());
        listDialog.style(ListDialog.STYLE_TWO);
        listDialog.title("选择审批人");
        listDialog.btnNum(2);
        listDialog.content("111");
        listDialog.setOnItemClickL((bean, position) -> {
            mPresenter.submitNextPerson(bean);
        });
        listDialog.setCancelable(false);
        listDialog.show();
    }

    @Override
    public void showOverDialog(boolean isOver) {
        String alterStr;
        if (!isOver) {
            alterStr = "您填写的申请利率优惠浮动比在您的权限范围内，将不走流程，确认继续？";
        } else {
            alterStr = "您填写的申请利率低于目标利率，将进入审批流程，是否继续？";
        }
        NormalDialog dialog = showAlterDialogTwo("提示", alterStr);
        dialog.setOnBtnClickL(null, () -> {
            if (!isOver) {
                mPresenter.getApplyRateOnProcess(mPresenter.infoEntity);
            } else {
                mPresenter.getCalculateApplyRate(mPresenter.infoEntity);
            }
            dialog.dismiss();
        });
    }

    @Override
    public void showLoading() {
        if (spotsDialog == null) {
            spotsDialog = new SpotsDialog(this, "加载中");
        }
        spotsDialog.show();
    }

    @Override
    public void hideLoading() {
        if (spotsDialog != null) {
            spotsDialog.dismiss();
        }
    }

    @Override
    public void showError(String msg) {
        showToast(msg);
    }

    @Override
    public void resetView() {
        ivTop.setVisibility(View.GONE);
        hideResultView();
        if (isStock) {
            showCalculateInfo(getIntent().getParcelableExtra("info"));
        } else {
            showCalculateInfo(mPresenter.infoEntity);
//            layoutCalculateCustomer.setVisibility(View.VISIBLE);
//            layoutCalculateLoan.setVisibility(View.GONE);
//            layoutCalculateEnsure.setVisibility(View.GONE);
//            layoutCalculateTax.setVisibility(View.GONE);
//            layoutCustomerContent.setVisibility(View.GONE);
//            layoutLoanContent.setVisibility(View.GONE);
//            layoutEnsureContent.setVisibility(View.GONE);
//            layoutTaxContent.setVisibility(View.GONE);
//            tvAddCustomer.setVisibility(View.VISIBLE);
//            tvAddEnsure.setVisibility(View.GONE);
//            tvAddLoan.setVisibility(View.GONE);
//            layoutCalculatePromiseDetail.setVisibility(View.GONE);
//            btnCalculateMeasure.setVisibility(View.GONE);
//            btnCalculatePromise.setVisibility(View.VISIBLE);
//            layoutCalculateEnsureMoney.removeAllViews();
//            layoutCalculateEnsureMoney.setVisibility(View.GONE);
//            mPresenter.infoEntity.setResultInfoEntity(null);
//            mPresenter.infoEntity.setPromiseApplyEntity(null);
//            mPresenter.infoEntity.setClientInfoEntity(null);
//            mPresenter.infoEntity.setEnsureInfoEntity(null);
//            mPresenter.infoEntity.setLoanInfoEntity(null);
//            etCalculatePromiseCash.setEnabled(true);
        }
    }

    @Override
    public void showApplyView() {
        if (type != AppConstant.LOAN_CALCULATE) {
            layoutCalculateApply.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onRecycle();
        }
    }
}
